import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import config from '../config'
import store from '@/store'

Vue.use(Router)
const router = new Router({
  scrollBehavior (to, from, savedPosition) {
    // if (savedPosition) {
    //   return savedPosition
    // } else {
    //   return { x: 0, y: 0 }
    // }
  },
  routes,
  mode: 'hash'
})

router.beforeEach((to, from, next) => {
  if ((!store.state.user.token || !store.state.user.severUserInfo || !store.state.user.severUserInfo.member_id) &&
    to.path !== '/login' &&
    to.path !== '/register' &&
    to.path !== '/policy') {
    next()
    var tokenStr = window.sessionStorage.getItem('token') // 更改路由守卫验证
    if (!tokenStr) {
      next()
    } else {
      next({
        name: config.homeName // 跳转到登录页
      })
    }
    // next({
    //   name: config.homeName // 跳转到登录页
    // })
  }
  if (to.name === 'main') {
    next({
      name: config.homeName // 跳转到登录页
    })
  }
  if (to.meta.title) {
    document.title = to.meta.title
  }
  // chrome
  document.body.scrollTop = 0
  // firefox
  document.documentElement.scrollTop = 0
  // safari
  window.pageYOffset = 0
  next()
})

router.afterEach(to => {
  window.scrollTo(0, 0)
})

export default router
